import 'dart:io';
import 'package:dotted_border/dotted_border.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:process_run/shell_run.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:win32/win32.dart';
import 'package:xlog_helper/decode_task.dart';
import 'dart:ffi';
import 'package:win32/win32.dart';

class LogDecoderHome extends StatefulWidget {
  const LogDecoderHome({super.key});

  @override
  State<LogDecoderHome> createState() => _LogDecoderHomeState();
}

class _LogDecoderHomeState extends State<LogDecoderHome> {
  String? _pythonScriptPath;
  final _shell = Shell();

  DecodeTask? _currentTask;
  List<DecodeTask> runningTasks = [];
  List<DecodeTask> resultTasks = [];

  @override
  void initState() {
    super.initState();
    _loadSavedScriptPath();
  }

  // 加载保存的Python脚本路径
  Future<void> _loadSavedScriptPath() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _pythonScriptPath = prefs.getString('python_script_path');
    });
  }

  // 选择Python脚本路径
  Future<void> _selectPythonScript() async {
    final typeGroup = XTypeGroup(label: 'Python Script', extensions: ['py']);
    final file = await openFile(acceptedTypeGroups: [typeGroup]);

    if (file != null) {
      setState(() {
        _pythonScriptPath = file.path;
      });

      // 保存路径到本地存储
      final prefs = await SharedPreferences.getInstance();
      prefs.setString('python_script_path', file.path);
    }
  }

  // 处理拖放的文件
  Future<void> _handleDroppedFile(List<DropItem> items) async {
    if (_pythonScriptPath == null || !File(_pythonScriptPath!).existsSync()) {
      _showErrorDialog('请先设置有效的解密脚本路径');
      return;
    }

    if (runningTasks.isNotEmpty == true) {
      _showErrorDialog("正在处理其他任务中");
      return;
    }

    var list = items.where(
      (e) =>
          (e.path.toLowerCase().endsWith('.xlog') ||
          e.path.toLowerCase().endsWith('.txt')),
    );
    if (list.isNotEmpty != true) {
      _showErrorDialog('请拖放.xlog或.txt格式的文件');
      return;
    }

    runningTasks = list.map((e) => DecodeTask(source: e.path)).toList();
    debugPrint("待解密文件:${runningTasks.length}");
    DecodeTask? task = runningTasks.firstOrNull;
    while (task != null) {
      await startDecode(task);
      DecodeTask? resultTask = resultTasks
          .where((e) => e.source == task?.source)
          .firstOrNull;
      if (resultTask != null) {
        resultTask.time = DateTime.now();
      } else {
        task.time = DateTime.now();
        resultTasks.add(task);
      }
      runningTasks.remove(task);
      task = runningTasks.firstOrNull;
    }

    setState(() {});
  }

  // 用系统默认程序打开解密文件
  void _openDecodedFile() {
    /*if (_currentDecodedFilePath != null) {
      Process.run('open', [_currentDecodedFilePath!]); // macOS
      if (Platform.isWindows) {
        Process.run('start', [_currentDecodedFilePath!]); // Windows
      }
    }*/
  }

  // 显示错误对话框
  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('错误'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Mars日志解密工具')),
      body: Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 脚本路径配置区域
            Container(
              margin: EdgeInsets.only(left: 8),
              child: Text(
                '解密脚本路径:',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(height: 4),
            GestureDetector(
              onTap: _selectPythonScript,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(8),
                ),
                padding: EdgeInsets.only(left: 12, top: 4, bottom: 4, right: 4),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        _pythonScriptPath ?? '未设置',
                        style: TextStyle(
                          color: _pythonScriptPath == null
                              ? Colors.red
                              : Colors.black,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Text(
                      '选择脚本',
                      style: TextStyle(color: Theme.of(context).primaryColor),
                    ),
                    Icon(
                      Icons.keyboard_arrow_right_rounded,
                      color: Colors.grey[400],
                    ),
                  ],
                ),
              ),
            ),
            // 拖放区域
            const SizedBox(height: 8),
            _buildDropZone(),
            SizedBox(height: 20),
            // 解密结果区域
            Container(
              margin: EdgeInsets.only(left: 8, right: 8),
              child: Row(
                children: [
                  Expanded(
                    child: const Text(
                      '解密结果:',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),

                  GestureDetector(
                    onTap: () {
                      setState(() {
                        resultTasks.clear();
                      });
                    },
                    child: Row(
                      children: [
                        Image.asset(
                          "resources/icon_clear.png",
                          height: 18,
                          color: Theme.of(context).primaryColor,
                        ),
                        Text(
                          '清空',
                          style: TextStyle(
                            fontSize: 16,
                            color: Theme.of(context).primaryColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),

            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: ListView.builder(
                  itemBuilder: (context, index) {
                    DecodeTask task = resultTasks[index];
                    return Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      margin: EdgeInsets.only(top: 8, left: 10, right: 12),
                      child: InkWell(
                        borderRadius: BorderRadius.circular(12),
                        onTap: (){
                          _launchOpenFile(task.destination);
                        },
                        child: Container(
                          padding: EdgeInsets.only(
                            left: 12,
                            top: 10,
                            bottom: 10,
                            right: 10,
                          ),

                          child: Row(
                            children: [
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      "${task.source}",
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.grey,
                                      ),
                                    ),
                                    Text("${task.destination}"),
                                  ],
                                ),
                              ),
                              if (File(task.destination).existsSync())
                                GestureDetector(
                                  onTap: () {
                                    openFileLocation(task.destination);
                                  },
                                  child: Image.asset("resources/icon_folder.png", height: 20, color: Theme.of(context).primaryColor,),
                                ),
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                  itemCount: resultTasks.length,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _launchOpenFile(String path) async {
    if (!await launchUrl(Uri.file(path))) {
      _showErrorDialog("无法打开文件:$path");
    }
  }

  Future<void> openFileLocation(String filePath) async {
    try {
      if (!File(filePath).existsSync()) {
        throw Exception('文件不存在: $filePath');
      }

      final file = File(filePath);
      final directory = file.parent.path;
      final fileName = file.path;

      debugPrint("打开文件夹:$fileName");

      if (Platform.isWindows) {
        openFileLocation2(filePath);
        // Windows: 使用explorer命令，/select参数选中文件
        // var result = await Process.run('explorer.exe', ['/select', '"$filePath"'], runInShell: true);
        // debugPrint("打开结果:${result.stderr} / ${result.stdout} / ${result.exitCode}");
      } else if (Platform.isMacOS) {
        // macOS: 使用open命令，-R参数显示文件在Finder中的位置
        await Process.run('open', ['-R', fileName]);
      } else if (Platform.isLinux) {
        // Linux: 使用xdg-open打开文件夹（无法直接选中文件，只能打开文件夹）
        await Process.run('xdg-open', [directory]);
      } else {
        throw Exception('不支持的平台');
      }
    } catch (e) {
      throw PlatformException(
        code: 'OPEN_FAILED',
        message: '无法打开文件位置: ${e.toString()}',
      );
    }
  }

  void openFileLocation2(String filePath) {
    final lpOperation = TEXT('open');
    final lpFile = TEXT('explorer.exe');
    final lpParameters = TEXT('/select,"$filePath"');
    final lpDirectory = nullptr;
    final nShowCmd = SW_SHOWNORMAL;

    final result = ShellExecute(
      0,
      lpOperation,
      lpFile,
      lpParameters,
      lpDirectory,
      nShowCmd,
    );

    if (result <= 32) {
      throw Exception('打开失败，错误码: $result');
    }
  }

  DropEventDetails? _draggingEvent;

  bool get _dropEnter => _draggingEvent != null;

  // 构建拖放区域
  Widget _buildDropZone() {
    return DropTarget(
      onDragDone: (data) => _handleDroppedFile(data.files),
      onDragEntered: (data) {
        setState(() {
          _draggingEvent = data;
        });
      },
      onDragExited: (data) {
        setState(() {
          _draggingEvent = null;
        });
      },
      child: DottedBorder(
        options: RoundedRectDottedBorderOptions(
          dashPattern: [10, 4],
          strokeWidth: 2,
          radius: Radius.circular(8),
          color: (_dropEnter ? Colors.blue : Colors.grey),
        ),
        child: Container(
          height: 150,
          decoration: BoxDecoration(
            color: _dropEnter ? Colors.blue[100] : Colors.grey[100],
            borderRadius: BorderRadius.circular(8),
          ),
          child: Stack(
            children: [
              if (_currentTask != null)
                Center(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      CircularProgressIndicator(strokeWidth: 2),
                      SizedBox(height: 8),
                      Text("正在解密，剩余 ${runningTasks.length} 个文件"),
                      Text(_currentTask?.source ?? ""),
                    ],
                  ),
                ),
              if (_currentTask == null)
                Center(
                  child: Text(
                    _draggingEvent != null ? "松开开始自动解密" : '请将.xlog或.txt文件拖放到此处',
                    style: TextStyle(
                      fontSize: 18,
                      color: _draggingEvent != null
                          ? Colors.black
                          : Colors.grey,
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> startDecode(DecodeTask task) async {
    setState(() {
      _currentTask = task;
    });

    try {
      // 生成输出文件路径
      String filePath = _currentTask?.source ?? "";

      // 构建解密命令
      String command;
      if (Platform.isWindows) {
        command = 'python "$_pythonScriptPath" "$filePath"'; //
      } else {
        // macOS可能需要使用python3
        command = 'python3 "$_pythonScriptPath" "$filePath"'; //
      }

      debugPrint("执行指令:$command");
      // 执行解密命令
      var result = await _shell.run(command);

      debugPrint("命令执行结果:${result.map((e) => e.stdout).join("")}");
      _currentTask?.error = result.map((e) => e.stderr).join("");
    } catch (e) {
      debugPrint("解密失败:$e");
      _showErrorDialog('解密失败: ${e.toString()}');
    } finally {
      setState(() {
        _currentTask = null;
      });
    }
  }
}
